package cn.weekimwee.firstlineofcodeforkotlin.unit8

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.View
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_play_video.*
import org.jetbrains.anko.toast
import java.io.File

class PlayVideoActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_play_video)
        play.setOnClickListener { it.onClick() }
        pause.setOnClickListener { it.onClick() }
        stop.setOnClickListener { it.onClick() }
        if (ContextCompat.checkSelfPermission(this@PlayVideoActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this@PlayVideoActivity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
        } else {
            initVideoPath()
        }
    }

    private fun initVideoPath(){
        videoView.setVideoPath(File(Environment.getExternalStorageDirectory(),"movie.mp4").path)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> {
                if (grantResults.isNotEmpty()  && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initVideoPath()
                } else {
                    toast("拒绝权限将无法使用程序")
                }
            }
        }
    }

    private fun View.onClick(){
        when(this.id){
            R.id.play->{
                if(!videoView.isPlaying) videoView.start()
            }
            R.id.pause->{
                if(videoView.isPlaying) videoView.pause()
            }
            R.id.stop->{
                if(videoView.isPlaying) videoView.resume()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        videoView.suspend()
    }
}
